/**
 * 物理拓扑图
 * Created by liupan on 2017/3/1.
 */
define(["require", "jquery", "public/app"], function (require, $, app) {

    function Topo($container) {
        this._$container = $container;
        this._init();
    }

    Topo.prototype._initUrlPath = function () {
        this.urlPaths = {
            HostData: app.urlBuild("/dirms/monitor/host/get/"),
            queryHostGroup: app.urlBuild("/dirms/monitor/group/query/distnetwork2")
        }
    };

    Topo.prototype._init = function () {
        this._initUrlPath();
        var self = this;
        var dataReady = app.getDataReady();

        dataReady.pushDataSource({//逐个放入所有数据源
            url: this.urlPaths.HostData,
            key: 'HostData'
        });

        dataReady.pushDataSource({//逐个放入所有数据源
            url: this.urlPaths.queryHostGroup,
            key: 'queryHostGroupData'
        });

        dataReady.once(function (readyData) {
            self._initComponents(readyData);
        });
    };

    Topo.prototype._initComponents = function (readyData) {
        //初始化控件
        this._initTopoGraph(readyData);//初始化用户表格
        // this._initEventBinding(this);//初始化事件绑定
        // this._initSearch();//初始化搜索
    };

    Topo.prototype._initSearch = function () {
        var self = this;
        //主表格搜索框
        $('#searchMenu').searchbox({
            //搜索功能未完成，应按照用户、角色、组织机构三类来进行搜索
            searcher: function (value,name) {
                if(name=='name'){
                }else if(name=='userName'){
                    if(value != ""){
                        $.ajax({
                            type:"GET",
                            url:self.urlPaths.findUesrDataByName+value,
                            success:function(data){
                                if(data==""||data==null){alert(value+" 用户不存在");}
                                else{
                                    $('#_UserGrid').datagrid('loadData',data);
                                    $('#searchMenu').searchbox('clear');
                                }
                            },
                            error:function(){alert("查询错误");}
                        });
                    }
                    else{
                        $('#_UserGrid').datagrid('reload');
                    }
                }
            },
            menu: '#search',
            prompt: '请输入关键字'
        });
    };

    Topo.prototype._showJTopToobar = function (stage) {

        var toobarDiv = $('<div class="jtopo_toolbar">').html('' + '<input type="radio" name="modeRadio" value="normal" checked id="r1"/>' + '<label for="r1"> 默认</label>' + '&nbsp;<input type="radio" name="modeRadio" value="select" id="r2"/><label for="r2"> 框选</label>' + '&nbsp;<input type="radio" name="modeRadio" value="edit" id="r4"/><label for="r4"> 加线</label>' + '&nbsp;&nbsp;<input type="button" id="centerButton" value="居中显示"/>' + '<input type="button" id="fullScreenButton" value="全屏显示"/>' + '<input type="button" id="zoomOutButton" value=" 放 大 " />' + '<input type="button" id="zoomInButton" value=" 缩 小 " />' + '&nbsp;&nbsp;<input type="checkbox" id="zoomCheckbox"/><label for="zoomCheckbox">鼠标缩放</label>' + '&nbsp;&nbsp;<input type="text" id="findText" style="width: 100px;" value="" onkeydown="enterPressHandler(event)">' + '<input type="button" id="findButton" value=" 查 询 ">' + '&nbsp;&nbsp;<input type="button" id="cloneButton" value="选中克隆">' + '&nbsp;&nbsp;<input type="button" id="exportButton" value="导出PNG">' + '&nbsp;&nbsp;<input type="button" id="printButton" value="导出PDF">');
        $('#content').prepend(toobarDiv);

        // 工具栏按钮处理
        $("input[name='modeRadio']").click(function() {
            stage.mode = $("input[name='modeRadio']:checked").val();
        });
        $('#centerButton').click(function() {
            stage.centerAndZoom(); //缩放并居中显示
        });
        $('#zoomOutButton').click(function() {
            stage.zoomOut();
        });
        $('#zoomInButton').click(function() {
            stage.zoomIn();
        });
        $('#cloneButton').click(function() {
            stage.saveImageInfo();
        });
        $('#exportButton').click(function() {
            stage.saveImageInfo();
        });
        $('#printButton').click(function() {
            stage.saveImageInfo();
        });
        $('#zoomCheckbox').click(function() {
            if ($('#zoomCheckbox').is(':checked')) {
                stage.wheelZoom = 1.2; // 设置鼠标缩放比例
            } else {
                stage.wheelZoom = null; // 取消鼠标缩放比例
            }
        });
        $('#fullScreenButton').click(function() {
            runPrefixMethod(stage.canvas, "RequestFullScreen")
        });

        window.enterPressHandler = function(event) {
            if (event.keyCode == 13 || event.which == 13) {
                $('#findButton').click();
            }
        };

        // 查询
        $('#findButton').click(function() {
            var text = $('#findText').val().trim();
            //var nodes = stage.find('node[text="'+text+'"]');
            var scene = stage.childs[0];
            var nodes = scene.childs.filter(function(e) {
                return e instanceof JTopo.Node;
            });
            nodes = nodes.filter(function(e) {
                if (e.text == null) return false;
                return e.text.indexOf(text) != -1;
            });

            if (nodes.length > 0) {
                var node = nodes[0];
                node.selected = true;
                var location = node.getCenterLocation();
                // 查询到的节点居中显示
                stage.setCenter(location.x, location.y);

                function nodeFlash(node, n) {
                    if (n == 0) {
                        node.selected = false;
                        return;
                    };
                    node.selected = !node.selected;
                    setTimeout(function() {
                        nodeFlash(node, n - 1);
                    }, 300);
                }

                // 闪烁几下
                nodeFlash(node, 6);
            }
        });

        var runPrefixMethod = function(element, method) {
            var usablePrefixMethod;
            ["webkit", "moz", "ms", "o", ""].forEach(function(prefix) {
                if (usablePrefixMethod) return;
                if (prefix === "") {
                    // 无前缀，方法首字母小写
                    method = method.slice(0, 1).toLowerCase() + method.slice(1);
                }
                var typePrefixMethod = typeof element[prefix + method];
                if (typePrefixMethod + "" !== "undefined") {
                    if (typePrefixMethod === "function") {
                        usablePrefixMethod = element[prefix + method]();
                    } else {
                        usablePrefixMethod = element[prefix + method];
                    }
                }
            });

            return usablePrefixMethod;
        };
    };

    //初始化拓扑图
    Topo.prototype._initTopoGraph = function (readyData) {
        var self = this;
        var hostGroupData = readyData.queryHostGroupData.data.result;
        if (hostGroupData == undefined || hostGroupData == null || hostGroupData.length != 1) return;
        var hostGroupId = hostGroupData[0].groupid;

        $.ajax({
            url: self.urlPaths.HostData+hostGroupId,
            contentType: "application/json",
            type: "post",
            success: function (data) {//保存成功时，把后台返回的数据更新到树节点中。如：后台做的insert操作，此时需要把id更新到树节点中
                var topoData = data.result;

                var canvas = document.getElementById('topo-content');
                var stage = new JTopo.Stage(canvas);
                stage.canvas.width = self._$container.width();
                stage.canvas.height = self._$container.height();
                self._showJTopToobar(stage);

                var scene = new JTopo.Scene();
                scene.color = "#CCCCCC";

                function createNode(x, y, img, name){
                    var node = new JTopo.Node(name);
                    node.setImage(app.getBasePath()+'/images/app/topo/' + img, true);
                    node.setLocation(x, y);
                    scene.add(node);
                    return node;
                }

                function linkNode(nodeA, nodeZ){
                    var link = new JTopo.FoldLink(nodeA, nodeZ);
                    link.lineWidth = 3;
                    link.strokeColor = '255,255,0';
                    scene.add(link);
                    return link;
                }

                var cloudNode = createNode(self._$container.width()/2,self._$container.height()/2, 'router.png', "219.222.189.254");
                cloudNode.layout = {type: 'circle', radius: 300};

                $.each(topoData, function (index) {
                    var hostName = this.name;
                    var hostIp = this.host;

                    var node = createNode(scene.width * Math.random(), scene.height * Math.random(), "router2.png", hostName);
                    linkNode(cloudNode, node);
                });

                stage.add(scene);
                JTopo.layout.layoutNode(scene, cloudNode, true);
            },
            error: function (event, XMLHttpRequest, ajaxOptions, thrownError) {
                $.messagerShow("初始化拓扑图失败！");
            }
        });

    };


    /**
     * 事件绑定
     */
    Topo.prototype._initEventBinding = function (self) {
        //【todo 在此编写绑定事件的方法。如按钮需要绑定的click事件。建议按如下格式绑定，并将this作为参数传入】
        //egg
        //用户管理首页五个按钮
        this._$container.find('#adduser_btn').on('click', {self: this}, this._actions.adduserClick);
        this._$container.find('#edituser_btn').on('click', {self: this}, this._actions.edituserClick);
        this._$container.find('#deleteuser_btn').on('click', {self: this}, this._actions.deleteuserClick);
        this._$container.find('#resetpw_btn').on('click', {self: this}, this._actions.resetpwClick);
        this._$container.find('#distribteRole_btn').on('click', {self: this}, this._actions.distribteRoleClick);

        /*
         this._$container.find('#save_btn').on('click', {self: this}, this._actions.saveClick);
         */
        self._$container.find("#export_0").on("click", {self: this}, this._actions.export_0);
        self._$container.find("#export_1").on("click", {self: this}, this._actions.export_1);

    };


    /**
     * 在此定义此js用到的事件处理方法。如处理按钮click事件的方法
     * @type {{btcClick: Function}}
     */
    Topo.prototype._actions = {
        //【todo 在此定义此js用到的事件处理方法。如处理按钮click事件的方法】
        //添加用户按键方法
        adduserClick: function (evt) {
            //$('#useradd').form('clear');
            //$('#add').dialog('open');
            showUserDialog(evt);
        },

        //用户编辑按钮事件
        edituserClick:function(evt){
            //获取这一行内容
            var row = $("#_UserGrid").datagrid('getSelections');
            if (row == undefined||row.length==0 ) {
                $.messager.alert('提示',"请选择编辑对象",'info');
                return;
            }else if(row.length>1){
                $.messager.alert('提示',"只能选择单条记录",'info');
                return;
            }
            showUserDialog(evt,row);
        },

        //用户删除按钮事件
        deleteuserClick:function(evt){
            var row = $("#_UserGrid").datagrid('getSelections');
            if (row < 1) {
                //1-1.如果没有任何一行选中 则提示
                $.messager.alert("提示","请选择要操作的对象！", 'warning');
                return;
            }else if(row.length>1){
                $.messager.alert('提示',"只能选择单条记录",'info');
                return;
            }
            $.messager.confirm("用户数据删除","您确定要删除吗？", function(r) {
                if (r) {
                    /* if(row.length!=undefined){
                     for(var i=0;i<row.length;i++){
                     userIds.push(row[i].user_id);
                     }
                     }
                     var ids=userIds.join(",");*/
                    var url = evt.data.self.urlPaths.DelUserData+row[0].id;
                    $.ajax({
                        type:"DELETE",
                        url:url,
                        data:{"id":row[0].id},
                        dataType:"json",
                        success:function(data){
                            alert(1);
                            $("#_UserGrid").datagrid('reload');//重新加载列表数据
                            $.messager.alert('提示','删除用户成功!','info');
                        },
                        error:function(event, XMLHttpRequest, ajaxOptions, thrownError){
                            $.messager.alert('提示','删除用户失败!','info');
                        }
                    });
                }
            });
        },

        resetpwClick:function(evt){
            var row = $("#_UserGrid").datagrid('getSelections');
            if (row < 1) {
                $.messager.alert("提示","请选择要操作的对象！", 'warning');
                return;
            }else if(row.length>1){
                $.messager.alert('提示',"只能选择单条记录",'info');
                return;
            }
            $.messager.confirm("用户密码重置","您确定要重置密码吗？", function(r) {
                if (r) {
                    var url = evt.data.self.urlPaths.ResetPWData;
                    $.ajax({
                        type:"POST",
                        url:url,
                        data:{"id":row[0].id},
                        dataType:"json",
                        success:function(data){
                            $("#_UserGrid").datagrid('reload');//重新加载列表数据
                            $.messager.alert('提示','用户密码重置成功!','info');
                        },
                        error:function(event, XMLHttpRequest, ajaxOptions, thrownError){
                            $.messager.alert('提示','用户密码重置失败!','info');
                        }
                    });
                }
            });
        },

        distribteRoleClick:function(evt){
            var row = $("#_UserGrid").datagrid('getSelections');
            if (row < 1) {
                //1-1.如果没有任何一行选中 则提示
                $.messager.alert("提示","请选择要操作的对象！", 'warning');
                return;
            }else if(row.length>1){
                $.messager.alert('提示',"只能选择单条记录",'info');
                return;
            }
            distribteRoleDialog(evt,row);
        },
        export_0:function(evt){
            $.exportExcel(evt.data.self._$container.find("#_UserGrid"), "用户管理信息","用户管理信息列表", evt.data.self.urlPaths.actionExport_0);
        },
        export_1:function(evt){
            $.exportExcel(evt.data.self._$container.find("#_UserGrid"), "用户管理信息","用户管理信息列表", evt.data.self.urlPaths.actionExport_1);
        }

    };


    /**
     *
     * @param evt 点击时间
     * @param row  行记录数据
     */
    var showUserDialog = function(evt,row){
        var inputUrl =evt.data.self.urlPaths.UserAddorEdit;
        var title="";
        //判断是新增还是编辑
        if (typeof(row) != 'undefined'&&row.length==1) {
            title = '编辑用户';
        } else {
            title = '新增用户';
        }
        //对话框
        useraddOrEditdialog = $('<div id="user_addOrEdit"/>').dialog({
            title : title,
            top:100,
            width : 500,
            /*          height : 360,*/
            modal : true, //模式窗口：窗口背景不可操作
            resizable : false, //可拖动边框大小
            plain : true,
            href : inputUrl,
            buttons : [ {
                text : '确定',
                iconCls : 'icon-ok',
                plain : true,
                handler : function() {
                    //修改时 设置id为可用 新增是默认不可用
                    if (typeof(row) != 'undefined'&&row.length==1) {
                        $("#id").attr("disabled",false);
                    }
                    var userData = $("#useradd").serializeJsonStr();

                    var isValid = $('#useradd').form('validate');
                    if(!isValid){
                        return ;
                    }
                    $.ajax({
                        url:evt.data.self.urlPaths.SaveUserData,
                        type:"POST",
                        cache:false,
                        contentType: "application/json",
                        async : false,
                        dataType: "json",
                        data : userData,
                        beforeSend:function(XMLHttpRequest){
                            $.messager.progress({
                                title : '提示信息！',
                                text : '数据处理中，请稍后....'
                            });
                        },
                        success: function(data){
                            $.messager.progress('close');
                            if(typeof(data) != "undefined" && data !=null && data!=''){
                                $.messager.alert('提示','保存成功！','info');
                                $("#_UserGrid").datagrid('reload');//重新加载列表数据
                                $("#user_addOrEdit").dialog('destroy');//销毁对话框
                            }
                        },
                        error: function (event, XMLHttpRequest, ajaxOptions, thrownError) {
                            $.messager.progress('close');
                            $.messager.alert('提示','数据保存失败！','info')
                        }
                    });
                }
            }, {
                text : '取消',
                iconCls : 'icon-cancel',
                plain : true,
                handler : function() {
                    $("#user_addOrEdit").dialog('destroy');//销毁对话框
                }
            } ],
            onClose : function() {
                $(this).dialog('destroy');
            },
            onLoad : function() {
                /*user_input_form_init(evt);*/
                //编辑
                if(row != undefined&&row.length==1){
                    // var id=row[0].id;
                    $("#useradd").form("load",row[0]);
                    // $('#id').val(id);
                }
            }
        }).dialog('open');
    };

    var distribteRoleDialog = function(evt,row){
        /*var inputUrl =evt.data.self.urlPaths.UserAddorEdit;*/
        var inputUrl =evt.data.self.urlPaths.DistributeRaleData;
        var id = row[0].id;

        //对话框
        user_distribteRole_dialog = $('<div id="user_distribteRole"/>').dialog({
            title : '分配角色',
            top:100,
            width : 800,
            /*          height : 360,*/
            modal : true, //模式窗口：窗口背景不可操作
            resizable : false, //可拖动边框大小
            plain : true,
            href : inputUrl,
            buttons : [ {
                text : '确定',
                iconCls : 'icon-ok',
                plain : true,
                handler : function() {
                    $("#user_distribteRole").dialog('destroy');
                    //修改时 设置id为可用 新增是默认不可用

                }
            }, {
                text : '取消',
                iconCls : 'icon-cancel',
                plain : true,
                handler : function() {
                    $("#user_distribteRole").dialog('destroy');//销毁对话框
                }
            } ],
            onClose : function() {
                $(this).dialog('destroy');
            },
            onLoad : function() {
                //编辑
                if(row != undefined&&row.length==1){
                    // var id=row[0].id;
                    $("#distribteForm").form("load",row[0]);
                    // $('#id').val(id);
                    $('#existingRole').datagrid({
                        rownumbers: true,
                        pagination: true,
                        singleSelect: true,
                        url: evt.data.self.urlPaths.UserRoleData+'?id='+id,
                        method: 'get',
                        title: '选定角色',
                        width: 'auto',
                        height: '280px',
                        striped: true,

                        columns: [[
                            {field: 'id', title: '角色id', width: 200,hidden:true},
                            {field: 'ruid', title: '用户角色关系id', width: 200,hidden:true},
                            {field: 'name', title: '角色名称', width: 200}
                        ]]
                    });
                    //添加用户对话框右侧可选角色组表格
                    $('#availableRole').datagrid({
                        rownumbers: true,
                        pagination: true,
                        singleSelect: true,
                        url: evt.data.self.urlPaths.RoleData+'?id='+id,
                        method: 'get',
                        title: '可选角色',
                        width: 'auto',
                        height: '280px',
                        striped: true,

                        columns: [[
                            {field: 'id', title: '角色id', width: 200,hidden:true},
                            {field: 'name', title: '角色名称', width: 200}
                        ]]
                    });

                    /**
                     * 角色分配页面按钮事件
                     */
                    /* this._$container.find('#existSearch').on('click', {self: this}, this._actions.existSearchClick);


                     existSearchClick:function(evt){
                     alert(1);
                     var name = $("#existSearch").val();
                     $("#existingRole").datagrid('load', {
                     name : name
                     });
                     }*/
                    $('#existSearch').searchbox({
                        //搜索功能未完成，应按照用户、角色、组织机构三类来进行搜索
                        searcher: function (value,name) {
                            $("#existingRole").datagrid('load', {
                                name : value,
                                id:id
                            });
                        },
                        prompt: '请输入关键字'
                    });

                    $('#availableSearch').searchbox({
                        //搜索功能未完成，应按照用户、角色、组织机构三类来进行搜索
                        searcher: function (value,name) {
                            $("#availableRole").datagrid('load', {
                                name : value,
                                id:id
                            });
                        },
                        prompt: '请输入关键字'
                    });
                    //角色添加
                    $('#addRole_btn').on('click',{},function(){
                        var row = $("#availableRole").datagrid('getSelections');
                        //  var  roleName = app.utils.formToJSON({ofRole:row.name});
                        if (row < 1) {
                            //1-1.如果没有任何一行选中 则提示
                            $.messager.alert("提示","请选择要操作的对象！", 'warning');
                            return;
                        }else if(row.length>1){
                            $.messager.alert('提示',"只能选择单条记录",'info');
                            return;
                        }
                        $.ajax({
                            url:evt.data.self.urlPaths.SaveUserRoleData,
                            type:"POST",
                            cache:false,
                            contentType: "application/json",
                            async : false,
                            dataType: "json",
                            data : JSON.stringify({userId:id,roleId:row[0].id}),
                            success: function(data){
                                $("#existingRole").datagrid('load', {
                                    name : $('#existSearch').val(),
                                    id:id
                                });
                                $("#availableRole").datagrid('load', {
                                    name : $('#availableSearch').val(),
                                    id:id
                                });
                            },
                            error: function (event, XMLHttpRequest, ajaxOptions, thrownError) {
                                $.messager.alert('提示','添加失败！','info');
                            }
                        });



                    });
                    //角色移除
                    $('#removeRole_btn').on('click',{},function(){

                        var row = $("#existingRole").datagrid('getSelections');
                        if (row < 1) {
                            //1-1.如果没有任何一行选中 则提示
                            $.messager.alert("提示","请选择要操作的对象！", 'warning');
                            return;
                        }else if(row.length>1){
                            $.messager.alert('提示',"只能选择单条记录",'info');
                            return;
                        }
                        $.ajax({
                            url:evt.data.self.urlPaths.DelUserRoleData+row[0].id,
                            type:"DELETE",
                            cache:false,
                            contentType: "application/json",
                            async : false,
                            dataType: "json",
                            /*  data : {id:id,rid:row[0].id},*/
                            success: function(data){
                                $("#existingRole").datagrid('load', {
                                    name : $('#existSearch').val(),
                                    id:id
                                });
                                $("#availableRole").datagrid('load', {
                                    name : $('#availableSearch').val(),
                                    id:id
                                });
                            },
                            error: function (event, XMLHttpRequest, ajaxOptions, thrownError) {
                                $.messager.alert('提示','移除失败！','info');
                            }
                        });
                    });
                }
            }
        }).dialog('open');
    }

    /**
     * 隐藏密码,如果后期需要对特别用户提供展示，在此处修改
     * @param value
     * @param row
     * @param index
     */
    var passwordFormat = function(value,row,index){
        return "******";
    }

    return Topo;
});
